package de.sendorian.app.forumArchive.script;


import static org.junit.Assert.*;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Logger;

import org.junit.Test;

import de.sendorian.app.forumArchive.ArchiveBuilder;
import de.sendorian.app.forumArchive.domain.Forum;
import de.sendorian.app.forumArchive.domain.Topic;
import de.sendorian.app.forumArchive.repository.ForumRepository;
import de.sendorian.app.forumArchive.repository.TopicRepository;

public class DiagnosingScripts {

	private static Logger logger = Logger.getLogger(ArchiveBuilder.class.getName());

	@Test
	public void checkDuplicateTopicEntries() {
		List<String> duplicateTopics = new ArrayList<String>();
		List<Forum> forums = new ForumRepository().findAll();
		TopicRepository topicRepository = new TopicRepository();

		for (Forum forum : forums) {
			for (Topic topic : forum.getTopics()) {
				if (!duplicateTopics.contains(topic.getName())) {
					List<Topic> topics = topicRepository.findByAttribute("name", topic.getName());
					if (topics.size() > 1) {
						duplicateTopics.add(topic.getName());
					}
				}
			}
		}

		if (!duplicateTopics.isEmpty()) {
			String msg = "Database contains " + duplicateTopics.size() + " duplicate topics!";
			logger.warning(msg);
			logger.warning("" + duplicateTopics);
			fail(msg);
		}
	}

	@Test
	public void checkDuplicateTopicEntriesPerForum() {
		Set<String> duplicateTopics = new HashSet<String>();
		List<Forum> forums = new ForumRepository().findAll();

		for (Forum forum : forums) {
			for (Topic topic : forum.getTopics()) {
				if (!duplicateTopics.contains(topic.getName())) {
					for (Topic topic2 : forum.getTopics()) {
						if (topic.getName().equals(topic2.getName())) {
							duplicateTopics.add(topic.getName());
						}
					}
				}
			}
		}

		if (!duplicateTopics.isEmpty()) {
			String msg = "Forums contain " + duplicateTopics.size() + " duplicate topics!";
			logger.warning(msg);
			logger.warning("" + duplicateTopics);
			fail(msg);
		}
	}

}
